package graphic;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;

import javax.swing.*;

/**
 *
 * @author R�my
 */
public class ChatWindow extends JFrame implements Runnable{

    /**
	 * 
	 */
	private static final long serialVersionUID = -4268176950886359123L;
	private ControlGUI control;
	/**
     * Creates new form ChatWindow
     */
    public ChatWindow(ControlGUI cGUI) {
        initComponents();
        this.control = cGUI;
        this.sendButton.addActionListener(new SendButListener());
        this.textSendArea.addKeyListener(new TextListener());
        this.disconnectButton.addActionListener(new CoButListener());
        this.fileSendButton.addActionListener(new FileSendButListener());
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
       
        
    }

    private void exit() {
    	control.performDisconnect();
    	System.exit(0);
    }
   
    private void initComponents() {

        jPanel4 = new JPanel();
        jPanel1 = new JPanel();
        jScrollPane1 = new JScrollPane();
        chatRecvArea = new JTextArea();
        jPanel2 = new JPanel();
        jScrollPane2 = new JScrollPane();
        userList = new JList();
        jPanel5 = new JPanel();
        sendButton = new JButton();
        fileSendButton = new JButton();
        jPanel6 = new JPanel();
        disconnectButton = new JButton();
        jScrollPane3 = new JScrollPane();
        textSendArea = new JTextField();

        addWindowListener ( new WindowListener() {             
            public void windowClosing ( WindowEvent e ) { 
                exit();
            }
			public void windowActivated(WindowEvent arg0) {				
			}
			@Override
			public void windowClosed(WindowEvent arg0) {
				exit();
			}
			@Override
			public void windowDeactivated(WindowEvent arg0) {				
			}
			@Override
			public void windowDeiconified(WindowEvent arg0) {				
			}
			@Override
			public void windowIconified(WindowEvent arg0) {				
			}
			@Override
			public void windowOpened(WindowEvent arg0) {				
			} 
        });
        
        GroupLayout jPanel4Layout = new GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        

        chatRecvArea.setEditable(false);
        chatRecvArea.setColumns(20);
        chatRecvArea.setRows(5);
        jScrollPane1.setViewportView(chatRecvArea);

        GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
        );
        
        listModel = new DefaultListModel();
        userList.setModel(listModel);
        jScrollPane2.setViewportView(userList);

        GroupLayout jPanel2Layout = new GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)
        );

        sendButton.setText("Send");

        fileSendButton.setText("Send a file");

        GroupLayout jPanel5Layout = new GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGroup(jPanel5Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(sendButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(fileSendButton)))
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(sendButton)
                .addGap(18, 18, 18)
                .addComponent(fileSendButton)
                .addContainerGap(25, Short.MAX_VALUE))
        );

        disconnectButton.setText("Disconnect");

        GroupLayout jPanel6Layout = new GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addComponent(disconnectButton)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addComponent(disconnectButton)
                .addContainerGap(44, Short.MAX_VALUE))
        );

        textSendArea.setColumns(20);
        //textSendArea.setRows(5);
        jScrollPane3.setViewportView(textSendArea);

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addComponent(jScrollPane3, GroupLayout.DEFAULT_SIZE, 381, Short.MAX_VALUE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel5, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel6, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel6, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel5, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addContainerGap(23, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    public int setCloseOperation(){
    	control.performDisconnect();
    	return 0;
    }
    
    public void run() {
    	this.setVisible(true);
    }
    // Variables declaration - do not modify
    private JTextArea chatRecvArea;
    private JButton disconnectButton;
    private JButton fileSendButton;
    private JPanel jPanel1;
    private JPanel jPanel2;
    private JPanel jPanel4;
    private JPanel jPanel5;
    private JPanel jPanel6;
    private JScrollPane jScrollPane1;
    private JScrollPane jScrollPane2;
    private JScrollPane jScrollPane3;
    private JButton sendButton;
    private JTextField textSendArea;
    private JList userList;
    private DefaultListModel listModel;
    // End of variables declaration
    

	
	private void addToJList (String login) {    
    	listModel.addElement(login);
    	userList.setModel(listModel);
    }
	    
	private void removeFromJList (String login) {
		listModel.removeElement(login);
    	userList.setModel(listModel);
    }
	
	private String getUserNByLogin (String login){
		int i,j =0; boolean found = false;
		for (i=0;i<login.length();i++){
			if (login.charAt(i)!='@'){
				if (!found){
				j++;}
			}
			else {
				found = true;
			}
		}
		return login.substring(0,j);
	}

	public void showLocalConnect(String login) {
		this.chatRecvArea.append("You are now connected. Welcome !\n");
		this.addToJList(login);
	}

	public void showConnect(String login) {
		this.chatRecvArea.append(login+" is now connected.\n");
		this.addToJList(login);
	}

	public void showDisconnect(String login) {
		this.removeFromJList(login);
		login = this.getUserNByLogin(login);
		this.chatRecvArea.append(login+" is now disconnected.\n");
	}

	public void showText(String login, String text) {
		this.chatRecvArea.append("From "+ login +" : "+text+"\n");
		this.chatRecvArea.setCaretPosition(chatRecvArea.getDocument().getLength ()); 
	}

	public void showLocalDisconnect() {
		this.chatRecvArea.append("You are now disconnected. The connect window will soon appear.\n");
		while(listModel.getSize() != 0) {
			listModel.remove(0);
		}
		listModel.clear();
		this.userList.setModel(listModel);
	}
	
	
	public void showPropFile(String fileName, long fileSize, int fileID,
			String login) {
		boolean accepted = false; boolean now = true;
		this.chatRecvArea.append(login+" wants to send you a file :\n");
		this.chatRecvArea.append(fileName+" : "+fileSize+"o\n");
		String path = null;
		JFileChooser chooser = new JFileChooser("~");
		chooser.setSelectedFile(new File(fileName));
		int returnVal = chooser.showSaveDialog(getParent());
	    if(returnVal == JFileChooser.APPROVE_OPTION) {
	    	accepted = true;
	    	path = chooser.getSelectedFile().getAbsolutePath();
	    	chatRecvArea.append("File accepted : "+fileName+". Download will start soon.\n");
	    }
	    else {
	    	chatRecvArea.append("You have declined the file "+fileName+".\n");
	    }
		this.control.performAcceptFile(fileID,accepted,now,login,path);
	}
	
	
	public void setEdit (boolean editable){
		this.textSendArea.setEditable(editable);
	}
	
	private class SendButListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			if (control.getConnected()){
				int[] ind = userList.getSelectedIndices();
				if (ind.length>0) {
					String[] users= new String[ind.length];
					int j = 0;
					chatRecvArea.append("To : ");
					for(int i : ind){
						users[j] = (String) listModel.getElementAt(i); 
						chatRecvArea.append(users[j]+ ", ");
						j++;
					}
					chatRecvArea.append(" :\n");
					chatRecvArea.append(textSendArea.getText()+"\n");
					control.performSendText(users, textSendArea.getText());
					textSendArea.setText("");
				} 
			}
		}    	
    }
	
	private class CoButListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			if (control.getConnected()){
				control.performDisconnect();
			}
		}    	
    }
	
	private class FileSendButListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			if (control.getConnected()){
				int[] ind = userList.getSelectedIndices();
				if (ind.length>0) {
					for(int i : ind){
						String login = (String) listModel.getElementAt(i);
						JFileChooser chooser = new JFileChooser("~");
						int returnVal = chooser.showOpenDialog(getParent());
						if(returnVal == JFileChooser.APPROVE_OPTION) {
							File f = chooser.getSelectedFile();
							if (f.isFile()) {
								control.performPropFile(f.getName(),f.length(),login,f.getAbsolutePath());
							}
							else chatRecvArea.append("please select a file, not a repository");
						}
					}				
				}
			}
		}    	
    }
	
	 private class TextListener implements KeyListener {

			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER)
					if(control.getConnected())
					sendButton.doClick();
			}
			@Override
			public void keyReleased(KeyEvent e) {		
				if (e.getKeyCode() == KeyEvent.VK_ENTER)
					textSendArea.setText("");
			}
			@Override
			public void keyTyped(KeyEvent e) {
				//if (e.getKeyCode() == KeyEvent.VK_ENTER)
				//sendButton.doClick();
			}    	
	    }

	

	
	    
	
}
